﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Sklad1_2.Add;
using Sklad1_2.Add.Update;
using Sklad1_2.Data;
using Sklad1_2.Search;

namespace Sklad1_2
{
    public partial class Form1 : Form
    {
        private DBase aBase;
        
        private int id=0;
        DateTime t=new DateTime(2012,09,13);
        private double count2,price;
        private double count1;
        private bool flag = false;
        private int count3;
        private double price1;


        public Form1()
        {
            InitializeComponent();
            aBase = new DBase(Helper.ConnectionString);
            Initialize();
            Init();
            textBox1.Text = "0";
            textBox4.Text = "0";

            MaximizeBox = false;
            FileStream fs = new FileStream(Application.StartupPath + "//reg.txt", FileMode.Create, FileAccess.ReadWrite,
                                           FileShare.None);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(1);
        }

        #region Methods

        private void Initialize()
        {
            Clear();
            textBox1.ReadOnly = false;
            string main = Helper.QueryMain + " and f.ostatok<>0";
            aBase.AddItemDBGridView(dataGridView1, main);
            string zak = Helper.QueryZakupka+ " and a.ostatok<>0";
            aBase.AddItemDBGridView(dataGridView2, zak);
            aBase.AddItemDBGridView(dataGridView4,Helper.QueryVozvrat);
            aBase.AddItemDBGridView(dataGridView3, Helper.QueryVozvrat1);
            int summa1 = 0;
            for (int i = 0; i < dataGridView4.RowCount; i++)
            {
                summa1+=Int32.Parse(Convert.ToString(dataGridView4[4, i].Value));
            }
            toolStripStatusLabel1.Text ="Общяя сумма возврата="+ Convert.ToString(summa1);
            summa1 = 0;
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                summa1 += Int32.Parse(Convert.ToString(dataGridView3[3, i].Value));
            }
            toolStripStatusLabel2.Text ="Общяя сумма возврата="+ Convert.ToString(summa1);
            Visible();
        }

        private void Init()
        {
            aBase.AddItem(comboBox1, "customer");
            aBase.AddItem(comboBox2, "angar");
            aBase.AddItem(comboBox6, "angar");
        }

        private new void Visible()
        {
            Helper.Hidden(dataGridView1, 0, 1, 2, 3, 4,5,12);
            Helper.Hidden(dataGridView2,0,1,2,3,4);
        }

        private void Clear()
        {
            textBox1.Clear();
            textBox3.Clear();
        }

        private void Bind(object sender, FormClosedEventArgs formClosedEventArgs)
        {
            Initialize();
            Init();
        }
    

    #endregion

        #region ComboBox

        

        private void comboBox6_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof(Int32);
            if (comboBox6.SelectedValue != null)
            {
                if (comboBox6.SelectedValue.GetType() == t)
                {
                    aBase.AddItemCategory(comboBox7, Convert.ToInt32(comboBox6.SelectedValue));
                    if (comboBox7.SelectedValue == null)
                    {
                        comboBox8.DataSource = null;
                    }
                }
            }
            else
            {
                comboBox8.DataSource = null;
            }
        }

        private void comboBox7_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof(Int32);
            if (comboBox7.SelectedValue != null)
            {
                if (comboBox7.SelectedValue.GetType() == t)
                {
                    aBase.AddItemFirma(comboBox8, Convert.ToInt32(comboBox7.SelectedValue));
                    if (comboBox8.SelectedValue == null)
                    {
                        comboBox9.DataSource = null;
                    }
                }
            }
            else
            {
                comboBox9.DataSource = null;
            }
        }

        private void comboBox8_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof(Int32);
            if (comboBox8.SelectedValue != null)
            {
                if (comboBox8.SelectedValue.GetType() == t)
                {
                    aBase.AddItemProduct(comboBox9, Convert.ToInt32(comboBox8.SelectedValue));

                }
            }
            else
            {
                comboBox9.DataSource = null;
            }
        }

        private void comboBox9_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof(Int32);
            if (comboBox9.SelectedValue != null)
            {
                if (comboBox9.SelectedValue.GetType() == t)
                {
                    id = Convert.ToInt32(comboBox9.SelectedValue);
                    count3 = Int32.Parse(aBase.SelectField("product", "count1", "id", id));
                    price1 = Double.Parse(aBase.SelectField("product", "price", "id", id));
                }
            }
        }

        private void comboBox2_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof (Int32);
            if (comboBox2.SelectedValue != null)
            {
                if (comboBox2.SelectedValue.GetType() == t)
                {
                    aBase.AddItemCategory(comboBox3, Convert.ToInt32(comboBox2.SelectedValue));
                    if (comboBox3.SelectedValue == null)
                    {
                        comboBox4.DataSource = null;
                    }
                }
            }
            else
            {
                comboBox2.DataSource = null;
            }

        }

        private void comboBox3_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof (Int32);
            if (comboBox3.SelectedValue != null)
            {
                if (comboBox3.SelectedValue.GetType() == t)
                {
                    aBase.AddItemFirma(comboBox4, Convert.ToInt32(comboBox3.SelectedValue));
                    if (comboBox4.SelectedValue == null)
                    {
                        comboBox5.DataSource = null;
                    }
                }
            }
            else
            {
                comboBox3.DataSource = null;
            }
        }

        private void comboBox4_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof (Int32);
            if (comboBox4.SelectedValue != null)
            {
                if (comboBox4.SelectedValue.GetType() == t)
                {
                    aBase.AddItemProduct(comboBox5, Convert.ToInt32(comboBox4.SelectedValue));

                }
            }
            else
            {
                comboBox4.DataSource = null;
            }
        }

        private void comboBox5_SelectedValueChanged(object sender, EventArgs e)
        {
            Type t = typeof(Int32);
            if (comboBox5.SelectedValue != null)
            {
                if (comboBox5.SelectedValue.GetType() == t)
                {
                    id = Convert.ToInt32(comboBox5.SelectedValue);
                    count1 =Double.Parse(aBase.SelectField("product", "count1", "id", id));
                    price = Double.Parse(aBase.SelectField("product", "price", "id", id));
                }
            }

        }

        #endregion

        #region Menu

        private void закупокToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SearchZakupka aZakupka = new SearchZakupka();
            aZakupka.FormClosed += Bind;
            aZakupka.ShowDialog();
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void складToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddAngar addAngar = new AddAngar();
            addAngar.FormClosed += Bind;
            addAngar.ShowDialog();
        }

        private void категориюToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (aBase.SelectField("angar", "id", "id", 1).Length > 0 && aBase.SelectField("angar", "id", "id", 1)!="0")
            {
                AddCategory addCategory = new AddCategory();
                addCategory.FormClosed += Bind;
                addCategory.ShowDialog();
            }
            else
            {
                MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Складов!!!");
            }
        }

        private void фирмаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (aBase.SelectField("angar", "id", "id", 1).Length > 0 && aBase.SelectField("angar", "id", "id", 1) != "0")
            {
                if (aBase.SelectField("category", "id", "id", 1).Length > 0 && aBase.SelectField("category", "id", "id",1)!="0")
                {
                    AddFirma addFirma = new AddFirma();
                    addFirma.FormClosed += Bind;
                    addFirma.ShowDialog();
                }
                else
                {
                    MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Категорий!!!");
                }
            
            }
            else
            {
                MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Складов!!!");
            }
            
        }

        private void наименованиеТовараToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (aBase.SelectField("angar", "id", "id", 1).Length > 0 && aBase.SelectField("angar", "id", "id", 1) != "0")
            {
                if (aBase.SelectField("category", "id", "id", 1).Length > 0 &&aBase.SelectField("category", "id", "id", 1) != "0")
                {
                    if (aBase.SelectField("firma", "id", "id", 1).Length > 0 &&aBase.SelectField("firma", "id", "id", 1) != "0")
                    {
                        AddProduct addProduct = new AddProduct();
                        addProduct.FormClosed += Bind;
                        addProduct.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Фирм производителей!!!");
                    }
                }
                else
                {
                    MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Категорий!!!");
                }
            }
            else
            {
                MessageBox.Show("ВВЕДИТЕ СНАЧАЛА ЗНАЧЕНИЯ Складов!!!");
            }
        }

        private void клиентToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddClient addClient = new AddClient();
            addClient.FormClosed += Bind;
            addClient.ShowDialog();
        }

        private void оПрошраммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about=new About();
            about.ShowDialog();
        }

        private void заказовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SearchZakaz aSearchZakaz=new SearchZakaz();
            aSearchZakaz.FormClosed += Bind;
            aSearchZakaz.ShowDialog();
        }

        private void клиентовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SearchClient aClient=new SearchClient();
            aClient.FormClosed += Bind;
            aClient.ShowDialog();
        }

        private void товаровToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SearchProduct aProduct=new SearchProduct();
            aProduct.FormClosed += Bind;
            aProduct.ShowDialog();
        }
        #endregion

        #region RadioButton



        #endregion

        #region TextBox

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            if (textBox4.Text.Length > 0)
            {
                var t1 = Double.Parse(textBox4.Text);
                var res = t1 * count3;
                textBox5.Text = Convert.ToString(res);
            }
            else
            {
                textBox4.Text = "0";
            }
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            if (textBox5.Text.Length > 0)
            {
                var t1 = Double.Parse(textBox5.Text);
                var res = t1 * price1;
                textBox6.Text = Convert.ToString(res);
            }
            else
            {
                textBox5.Text = "0";
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            double summa=0;
            if (textBox1.Text.Length > 0)
            {
                var count = Int32.Parse(textBox1.Text);
                if (checkBox2.Checked)
                {
                    count2 = count*count1;
                    summa = count*count1*price;
                }
                else
                {
                    count2 = count;
                    summa = count*price;
                }
            }
            else
            {
                textBox1.Text = "0";
            }
            textBox2.Text = Convert.ToString(count2);
            textBox3.Text = Convert.ToString(summa);
           
        }
        #endregion

        #region Button

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox6.SelectedValue != null && comboBox7.SelectedValue != null && comboBox8.SelectedValue != null && comboBox9.SelectedValue != null)
            {
                string sklad = Convert.ToString(comboBox6.SelectedValue);
                string category = Convert.ToString(comboBox7.SelectedValue);
                string firma = Convert.ToString(comboBox8.SelectedValue);
                string product = Convert.ToString(comboBox9.SelectedValue);
                if (textBox4.Text.Length > 0)
                {
                    aBase.InsertValueSklad(sklad, category, firma, product, textBox4.Text, textBox5.Text, textBox6.Text,
                                           DateTime.Today.ToShortDateString());
                    Initialize();
                }
            }
            else
            {
                MessageBox.Show("Введите данные о клиентах,складах,категориях,товарах");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string quer = Helper.QueryVozvrat1;
            bool t1 = checkBox3.Checked;
            if (t1)
            {
                quer += " and a.datec1 between cdate('" + dateTimePicker2.Text + "') and cdate('" + dateTimePicker5.Text +
                        "')";
                aBase.AddItemDBGridView(dataGridView3, quer);
                int summa1 = 0;
                for (int i = 0; i < dataGridView3.RowCount; i++)
                {
                    summa1 += Int32.Parse(Convert.ToString(dataGridView3[3, i].Value));
                }
                toolStripStatusLabel2.Text = "Общяя сумма возврата=" + Convert.ToString(summa1);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string q = Helper.QueryVozvrat;
            if (checkBox1.Checked)
            {
                q += " and a.datec1 between cdate('" + dateTimePicker3.Text + "') and cdate('" + dateTimePicker4.Text + "')";
                aBase.AddItemDBGridView(dataGridView4, q);
                int summa1 = 0;
                for (int i = 0; i < dataGridView4.RowCount ; i++)
                {
                    summa1 += Int32.Parse(Convert.ToString(dataGridView4[4, i].Value));
                }
                toolStripStatusLabel1.Text = "Общяя сумма возврата=" + Convert.ToString(summa1);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {

            if (comboBox1.SelectedValue != null && comboBox2.SelectedValue != null && comboBox3.SelectedValue != null && comboBox4.SelectedValue != null && comboBox5.SelectedValue != null)
            {
                string customer = Convert.ToString(comboBox1.SelectedValue);
                string sklad = Convert.ToString(comboBox2.SelectedValue);
                string category = Convert.ToString(comboBox3.SelectedValue);
                string firma = Convert.ToString(comboBox4.SelectedValue);
                string product = Convert.ToString(comboBox5.SelectedValue);
                string summa = textBox3.Text;
                for (int i = 0; i < summa.Length; i++)
                {
                    if (summa[i] == ',')
                        summa.Replace(',', '.');
                }
                string date = dateTimePicker1.Text;
                string count3 = textBox2.Text;
                if ((textBox1.Text.Length > 0 && textBox1.Text != "0"))
                {
                    aBase.InsertValueMain(customer, sklad, category, firma, product, Convert.ToString(count2),
                                          Convert.ToString(count3), Convert.ToString(flag), summa, date);
                    Initialize();
                }
                else
                {
                    MessageBox.Show("Заполните все поля ввода!!!");
                }
            }
            else
            {
                MessageBox.Show("Введите данные о клиентах,складах,категориях,товарах");
            }
        }
        #endregion

        #region DataGridView

        private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1)
            {
                return;
            }
            List<string> data = new List<string>();
            Helper.Db2List(dataGridView2, e, ref data, 0, 1, 2, 3, 4, 9, 10, 11, 12, 13);
            UpdateZakupka aZakupka = new UpdateZakupka(data);
            aZakupka.FormClosed += Bind;
            aZakupka.ShowDialog();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex==-1||e.ColumnIndex==-1)
            {
                return;
            }
            var item = new List<string>();
            Helper.Db2List(dataGridView1,e,ref item,0,1,2,3,4,5,11,12,13,14,15,16,17);
            UpdateMain aUpdateMain=new UpdateMain(item);
            aUpdateMain.FormClosed += Bind;
            aUpdateMain.ShowDialog();

        }
        #endregion


        #region CheckBox
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePicker3.Enabled = dateTimePicker4.Enabled = checkBox1.Checked;
            if (!checkBox1.Checked)
            {
                aBase.AddItemDBGridView(dataGridView4, Helper.QueryVozvrat);
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            flag = checkBox2.Checked;
            textBox1_TextChanged(null,null);
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            string quer = Helper.QueryVozvrat1;
            bool t1;
            t1 = dateTimePicker2.Enabled = dateTimePicker5.Enabled = checkBox3.Checked;
            if (t1)
            {
                quer += " and a.datec1 between cdate('" + dateTimePicker2.Text + "') and cdate('" + dateTimePicker5.Text +
                        "')";
                aBase.AddItemDBGridView(dataGridView3, quer);
            }
            else
            {
                aBase.AddItemDBGridView(dataGridView3,quer);
            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            //StreamReader sr = new StreamReader("reg.txt");
            //string a = sr.ReadLine();
            //if (a == "1")
            //{
            //    Application.Exit();
            //}
            //sr.Close();
            

            /*using (FileStream fs = new FileStream(Application.StartupPath + "//reg.txt", FileMode.Create))
            {
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                if (t.ToShortDateString()== DateTime.Now.ToShortDateString())
                {
                    sw.WriteLine("1");
                    MessageBox.Show("1");
                    Application.Exit();
                    fs.Close();
                }
                else
                {
                    sw=new StreamWriter(fs,Encoding.UTF8);
                    sw.WriteLine("0");
                    fs.Close();
                }
            }
            
            using (FileStream fs = new FileStream(Application.StartupPath + "//reg.txt", FileMode.Open))
            {
                
            }*/
            
        }

        

        

        



    }
}

